<template>
  <view class="order">
    <!-- 导航栏 -->
    <view class="order-title">
      <view>我的订单</view>
      <button class="all-orders-btn" @click="goToAllOrders">全部订单 ></button>
    </view>

    <!-- 导航指示器 -->
    <view class="indicator">
      <view v-for="(item, index) in tabs"
            :key="index"
            class="indicator-item"
            :class="{ active: currentTab === index }"
            @click="tabClick(index)">
        <image class="indicator-icon" :src="item.icon" mode=""></image>
        <text class="title">{{ item.title }}</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-container">
    <!-- 进行中 -->
      <view v-if="currentTab === 0" class="content" >
        <view class="order-list" v-if="orders.processing.length > 0">
          <view v-for="(order, index) in orders.processing" :key="index"  class="order-item">
            <view>订单编号：{{ order.orderId }}</view>s
            <view>店名：{{ order.shopName }}</view>
            <view>球桌编号：{{ order.tableNumber }}</view>
            <view>开始时间：{{ order.createdTime }}</view>
            <view>已开台：{{ timeElapsed[order.orderId] || '0分0秒' }}</view>
            <view>结束时间：{{ order.endTime || '进行中...' }}</view>
            <view>创建时间：{{ order.createdTime }}</view>

            <!-- 新增：结束订单按钮 -->
            <button class="end-button" @click="endOrder(index)">结束订单</button>

          </view>
        </view>
        <view v-else class="empty-tip">暂无进行中的订单</view>
      </view>

      <!-- 待付款 -->
      <view v-if="currentTab === 1" class="content">
        <view v-if="orders.pendingPayment.length > 0">
          <view class="order-item" v-for="(order, idx) in orders.pendingPayment" :key="idx">
            <view v-if="order.isAutoSettled" style="color: red;">（超时自动结算）</view>
            <view>订单编号：{{ order.orderId }}</view>
            <view>店名：{{ order.shopName }}</view>
            <view>球桌编号：{{ order.tableNumber }}</view>
            <view>创建时间：{{ order.createdTime }}</view>
            <view>结束时间：{{ formatTime(order.endTime) }}</view>
            <view>使用时长：{{ order.duration || '未记录' }}</view>
            <view>订单金额：¥{{ order.totalPrice }}</view>
            <!--付款按钮 -->
            <button class="pay-button" @click="goToPay(order)">付款</button>
          </view>
        </view>
        <view v-else class="empty-tip">暂无待付款订单</view>
      </view>


      <!-- 待评价 -->
      <view v-if="currentTab === 2" class="content">
        <view v-if="orders.toReview.length > 0">
          <view class="order-item" v-for="(order, idx) in orders.toReview" :key="idx">
            <view>订单编号：{{ order.orderId }}</view>
            <view>店名：{{ order.shopName }}</view>
            <view>订单金额：¥{{ order.totalPrice }}</view>
            <view>使用时长：{{ order.duration || '未记录' }}</view>
            <!-- 可以加个按钮触发评价 -->
            <button class="evaluation-button" @click="goToReview(order)">去评价</button>
          </view>
        </view>
        <view v-else class="empty-tip">暂无待评价订单</view>
      </view>

      <!-- 待使用 -->
      <view v-if="currentTab === 3" class="content">
        <view v-if="orders.toView.length > 0">
          <view class="order-item" v-for="(order, idx) in formattedOrders" :key="idx">
            <view v-if="order.isTimedOut" style="color: red;">该订单已超时，只能申请退款</view>
            <view>店铺名称：{{ order.shopName }}</view>
            <view>球桌编号：{{ order.tableNumber }}</view>
            <view>开始时间：{{ order.startTime }}</view>
            <view>结束时间：{{ order.endTime }}</view>
            <view>创建时间：{{ order.createdTime }}</view>

            <!-- “去使用”按钮根据是否超时禁用 -->
            <button
                class="use-button"
                @click="goToUse(order)"
                :disabled="order.isTimedOut"
            >
              去使用
            </button>
            <!-- 退款按钮始终可用 -->
            <button class="refund-button" @click="refundOrder(order)">申请退款</button>
          </view>
        </view>
        <view v-else class="empty-tip">暂无待使用订单</view>
      </view>

    </view>

    <!-- 支付弹窗 -->
    <view v-if="showPaymentDialog" class="payment-dialog">
      <view class="dialog-overlay" @click.self="closePaymentDialog"></view>
      <view class="dialog-content">

        <view class="dialog-header">
          <text>选择支付方式</text>
          <image class="close-icon" src="/static/img/close.png" @click="closePaymentDialog" />
        </view>
        <!-- 新增：支付方式选择 -->
        <view class="payment-methods">
          <view v-for="method in paymentMethods" :key="method.id" class="method-item" @click="selectPaymentMethod(method.id)">
            <image class="method-icon" :src="method.icon" mode="aspectFit" />
            <text class="method-name">{{ method.name }}</text>
            <image v-if="selectedPaymentMethod === method.id" class="checkmark" src="/static/img/checkmark.png" mode="aspectFit" />
          </view>
        </view>

        <view class="dialog-body">
          <view class="amount">金额：¥{{ selectedOrder.totalPrice }}</view>
          <button class="pay-now-button" @click="confirmPayment">立即支付</button>
        </view>

      </view>
    </view>

  </view>
</template>


<script>
export default {
  data() {
    return {
      currentTab: 0, // 当前选中的导航索引
      tabs: [
        { title: '进行中', icon: '/static/img/order1.png'},
        { title: '待付款', icon: '/static/img/order2.png' },
        { title: '待评价', icon: '/static/img/order3.png' },
        { title: '待使用', icon: '/static/img/order4.png' }
      ],
      orders: {
        processing: [],
        pendingPayment: [],
        toReview: [],
        toView: []
      },
      selectedPaymentMethod: 'wechat', // 默认选择微信支付
      paymentMethods: [
        { id: 'wechat', name: '微信支付', icon: '/static/img/wechat-pay.png' },
        { id: 'alipay', name: '支付宝支付', icon: '/static/img/alipay-pay.png' },
        { id: 'balance', name: '余额支付', icon: '/static/img/balance.png' }
      ],
      timer: null, // 用于保存计时器
      timeElapsed: {}, // 存储每个订单的已用时间
      showPaymentDialog: false,
      selectedOrder: null, // 当前选中的待支付订单
      checkInterval: null // 定时检查器
    };
  },
  computed: {
    formattedOrders() {
      const now = new Date().getTime();
      return this.orders.toView.map(order => {
        const scheduledStartTime = order.scheduledStartTime;
        const tenMinutesLater = scheduledStartTime + 10 * 60 * 1000; // 10分钟后的时间戳
        return {
          ...order,
          isTimedOut: now >= tenMinutesLater
        };
      });
    }
  },
  onLoad() {
    this.loadCurrentOrder();
    uni.$on('newPendingOrder', this.handleNewPendingOrder);
  },
  onShow() {
    this.loadCurrentOrder(); // 强制重新加载订单数据
    this.startTimer();
    this.checkPendingOrdersTimeout(); // 检查超时订单
    this.startCheckOccupiedStatus();

    uni.$on('updateOrders', this.loadCurrentOrder);
  },
  onUnload() {
    this.stopTimer(); // 页面卸载时停止计时器
    uni.$off('newPendingOrder', this.handleNewPendingOrder); // 页面卸载时移除监听
    uni.$off('updateOrders', this.loadCurrentOrder); // 移除监听
    this.stopCheckOccupiedStatus();

    // 新增：清空待评价订单数据
    this.orders.toReview = [];
    const ordersList = uni.getStorageSync('ordersList') || [];
    const filteredOrders = ordersList.filter(order => order.status !== 'toReview');
    uni.setStorageSync('ordersList', filteredOrders); // 更新本地存储
  },

  methods: {

    loadCurrentOrder() {
      const ordersList = uni.getStorageSync('ordersList') || [];

      this.orders.processing = ordersList.filter(order => order.status === 'processing');
      this.orders.pendingPayment = ordersList.filter(order => order.status === 'pendingPayment');
      this.orders.toReview = ordersList.filter(order => order.status === 'toReview');
      this.orders.toView = ordersList.filter(order => order.status === 'pendingUse');
    },
    // 点击导航栏切换
    tabClick(index) {
      this.currentTab = index;
    },
    // 添加新订单到“待使用”列表
    handleNewPendingOrder(order) {
      this.orders.toView.unshift(order);
      uni.setStorageSync('ordersList', [...uni.getStorageSync('ordersList') || [], order]); // 可选：持久化保存
    },
    // 检查超时订单的方法
    checkPendingOrdersTimeout() {
      const now = new Date().getTime();
      const pendingOrders = this.orders.toView;

      pendingOrders.forEach(order => {
        const scheduledStartTime = order.scheduledStartTime;
        const tenMinutesLater = scheduledStartTime + 10 * 60 * 1000; // 10分钟后的时间戳

        if (now >= tenMinutesLater && !order.isConfirmed) {
          // 不再调用 handleAutoRefund，只是更新订单状态字段
          let ordersList = uni.getStorageSync('ordersList') || [];
          const targetIndex = ordersList.findIndex(o => o.orderId === order.orderId);

          if (targetIndex > -1) {
            ordersList[targetIndex].isTimedOut = true; // 添加一个字段表示已超时
            uni.setStorageSync('ordersList', ordersList);
          }
          // 释放球桌占用
          let occupiedTables = uni.getStorageSync('occupiedTables') || [];
          if (order.tableNumber && occupiedTables.includes(order.tableNumber)) {
            occupiedTables = occupiedTables.filter(num => num !== order.tableNumber);
            uni.setStorageSync('occupiedTables', occupiedTables);
          }

          uni.$emit('updateOccupiedTables');
          this.loadCurrentOrder(); // 刷新数据
        }
      });
    },
    handleAutoRefund(order) {
      uni.showToast({ title: '订单已超时', icon: 'none' });

      // 更新订单状态为 "refunded"
      let ordersList = uni.getStorageSync('ordersList') || [];
      const targetIndex = ordersList.findIndex(o => o.orderId === order.orderId);
      if (targetIndex > -1) {
        ordersList[targetIndex].status = 'refunded';
        uni.setStorageSync('ordersList', ordersList);
      }
      // 释放球桌占用
      let occupiedTables = uni.getStorageSync('occupiedTables') || [];
      if (order.tableNumber && occupiedTables.includes(order.tableNumber)) {
        occupiedTables = occupiedTables.filter(num => num !== order.tableNumber);
        uni.setStorageSync('occupiedTables', occupiedTables);
      }
      this.loadCurrentOrder(); // 刷新页面数据
    },
    startCheckOccupiedStatus() {
      this.checkInterval = setInterval(() => {
        uni.$emit('updateOccupiedTables'); // 广播更新事件
      }, 5000); // 每5秒广播一次
    },
    stopCheckOccupiedStatus() {
      if (this.checkInterval) {
        clearInterval(this.checkInterval);
        this.checkInterval = null;
      }
    },
    // 结束订单
    endOrder(index) {
      const endedOrder = this.orders.processing[index];
      // 获取当前时间戳
      const now = new Date().getTime();
      const duration = this.formatDuration(endedOrder.startTime, now);

      // 计算分钟数（向上取整）
      const diffMs = Math.max(0, now - endedOrder.startTime);
      const minutes = Math.ceil(diffMs / 60000); // 向上取整到分钟

      // 计算总价：价格 * 分钟数
      const totalPrice = (endedOrder.price * minutes).toFixed(2);

      // 删除前先释放球桌
      let occupiedTables = uni.getStorageSync('occupiedTables') || [];
      if (endedOrder.tableNumber && occupiedTables.includes(endedOrder.tableNumber)) {
        occupiedTables = occupiedTables.filter(num => num !== endedOrder.tableNumber);
        uni.setStorageSync('occupiedTables', occupiedTables);
      }

      // 更新订单状态、结束时间和计时时长
      endedOrder.endTime = now;
      endedOrder.duration = duration;
      endedOrder.totalPrice = totalPrice; // 添加总价字段
      endedOrder.status = 'pendingPayment';


      // 保存更新后的订单列表
      let ordersList = uni.getStorageSync('ordersList') || [];
      const targetIndex = ordersList.findIndex(order => order.orderId === endedOrder.orderId);
      if (targetIndex > -1) {
        ordersList.splice(targetIndex, 1, endedOrder);
      } else {
        ordersList.push(endedOrder);
      }
      uni.setStorageSync('ordersList', ordersList);
      this.loadCurrentOrder(); // 立即刷新数据，避免依赖 onShow

    },
    startTimer() {
      this.stopTimer(); // 避免重复启动
      this.timer = setInterval(() => {
        const now = new Date().getTime();
        const processingOrders = this.orders.processing;

        const elapsed = {};
        processingOrders.forEach(order => {
          if (order.startTime) {
            const diffMs = Math.max(0, now - order.startTime);
            const minutes = Math.floor(diffMs / 60000);
            const seconds = Math.floor((diffMs % 60000) / 1000);
            elapsed[order.orderId] = `${minutes}分${seconds}秒`;
          }
        });
        this.timeElapsed = elapsed;
      }, 1000);
    },
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleString();
    },
    // 在 methods 中新增一个方法用于格式化时间差
    formatDuration(startTime, endTime) {
      const diffMs = Math.max(0, endTime - startTime);
      const minutes = Math.floor(diffMs / 60000);
      const seconds = Math.floor((diffMs % 60000) / 1000);
      return `${minutes}分${seconds}秒`;
    },
    goToPay(order) {
      this.selectedOrder = order;
      this.showPaymentDialog = true;
    },
    goToAllOrders() {
      uni.navigateTo({
        url: '/pages/tabbar/tabbar-4-detail/order-list'
      });
    },
    closePaymentDialog() {
      this.showPaymentDialog = false;
    },
    confirmPayment() {
      if (!this.selectedOrder) return;

      const orderId = this.selectedOrder.orderId;
      const totalPrice = this.selectedOrder.totalPrice;

      if (this.selectedPaymentMethod === 'balance') {
        // 调用余额支付方法
        this.balancePay(totalPrice, orderId);
        return;
      }
      // 模拟微信/支付宝支付成功或失败
      uni.showModal({
        title: '确认支付',
        content: `是否使用 ${this.selectedPaymentMethod === 'wechat' ? '微信' : '支付宝'} 支付 ¥${totalPrice}？`,
        success: (res) => {
          if (res.confirm) {
            // 用户点击确定，模拟支付成功
            uni.showToast({ title: '支付成功', icon: 'success' });

            // 更新订单状态为 "toReview"
            let ordersList = uni.getStorageSync('ordersList') || [];
            const targetIndex = ordersList.findIndex(order => order.orderId === orderId);
            if (targetIndex > -1) {
              ordersList[targetIndex].status = 'toReview';
              uni.setStorageSync('ordersList', ordersList);
            }
            this.showPaymentDialog = false;
            this.loadCurrentOrder(); // 刷新页面数据
          } else if (res.cancel) {
            // 用户点击取消，模拟支付失败
            uni.showToast({ title: '支付失败', icon: 'none' });
          }
        }
      });
    },
    selectPaymentMethod(methodId) {
      this.selectedPaymentMethod = methodId;
    },
    balancePay(amount, orderId) {
      const currentBalance = this.$store.state.balanceAndPoints.balance;

      if (currentBalance < amount) {
        uni.showToast({ title: '余额不足', icon: 'none' });
        return;
      }
      uni.showModal({
        title: '确认支付',
        content: `是否使用余额支付 ${amount} 元？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({ title: `余额支付成功！-${amount}元`, icon: 'success' });

            // 扣除余额
            const newBalance = currentBalance - amount;
            this.$store.dispatch('balanceAndPoints/updateBalance', newBalance);

            // 更新订单状态为 "toReview"
            let ordersList = uni.getStorageSync('ordersList') || [];
            const targetIndex = ordersList.findIndex(order => order.orderId === orderId);

            if (targetIndex > -1) {
              ordersList[targetIndex].status = 'toReview';
              uni.setStorageSync('ordersList', ordersList);
            }

            this.showPaymentDialog = false;
            this.loadCurrentOrder(); // 刷新页面数据
          }
        }
      });
    },
    goToUse(order) {
      const now = new Date().getTime();
      const scheduledStartTime = order.scheduledStartTime;
      const tenMinutesLater = scheduledStartTime + 10 * 60 * 1000;

      if (now >= tenMinutesLater) {
        uni.showToast({ title: '订单已超时，无法使用', icon: 'none' });
        return;
      }

      uni.showModal({
        title: '确认使用',
        content: '您确定要使用这张订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 用户点击确认，直接将订单转为进行中状态
            const processingOrder = {
              ...order,
              startTime: now, // 设置开始时间为当前时间
              status: 'processing',
              createdTime: new Date(now).toLocaleString(), // 可选：更新创建时间为当前时间
              isConfirmed: true // 可选标记，用于区分是否已确认
            };

            // 更新订单列表
            let ordersList = uni.getStorageSync('ordersList') || [];

            // 1. 删除原“待使用”订单
            ordersList = ordersList.filter(o => o.orderId !== order.orderId);

            // 2. 添加新的“进行中”订单
            ordersList.push(processingOrder);

            // 3. 存储回本地存储
            uni.setStorageSync('ordersList', ordersList);

            // 4. 刷新页面数据
            this.loadCurrentOrder();
          }
        }
      });
    },
    refundOrder(order) {
      uni.showModal({
        title: '申请退款',
        content: '您确定要申请退款吗？',
        success: (res) => {
          if (res.confirm) {
            // 判断支付方式并处理余额退还等逻辑...
            if (order.paymentType === 'balance') {
              const refundAmount = 60;
              const currentBalance = this.$store.state.balanceAndPoints.balance;
              const newBalance = currentBalance + refundAmount;
              this.$store.dispatch('balanceAndPoints/updateBalance', newBalance);
              uni.showToast({ title: `已退还 ${refundAmount} 元至余额`, icon: 'success' });
            } else if (order.paymentType === 'wechat' || order.paymentType === 'alipay') {
              uni.showToast({ title: '退款成功，请留意微信/支付宝通知', icon: 'success' });
            }

            // 👇 新增：释放球桌占用状态
            let occupiedTables = uni.getStorageSync('occupiedTables') || [];
            if (order.tableNumber && occupiedTables.includes(order.tableNumber)) {
              occupiedTables = occupiedTables.filter(num => num !== order.tableNumber);
              uni.setStorageSync('occupiedTables', occupiedTables);
            }

            // 更新订单状态为 "refunded"
            let ordersList = uni.getStorageSync('ordersList') || [];
            const targetIndex = ordersList.findIndex(o => o.orderId === order.orderId);
            if (targetIndex > -1) {
              ordersList[targetIndex].status = 'refunded';
              uni.setStorageSync('ordersList', ordersList);
            }
            this.loadCurrentOrder(); // 刷新页面数据

            // 👇 新增：触发球桌状态更新事件
            uni.$emit('updateOccupiedTables');
          }
        }
      });
    },
    // 跳转到评价页面
    goToReview(order) {
      const orderId = encodeURIComponent(JSON.stringify(order));
      uni.navigateTo({
        url: `/pages/tabbar/tabbar-4-detail/review?orderId=${orderId}`
      });
    }

  },

};
</script>

<style>
.all-orders-btn {
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
  padding: 0;
  margin: 0;
  border: none;
  text-align: right;
  flex: 1;
}

.end-button {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: #4caf50; /* 绿色 - 完成 */
}

.pay-button {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: #2196f3; /* 蓝色 - 支付 */
}

.evaluation-button{
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: rgb(240, 208, 78); /* 蓝色 - 支付 */
}

.use-button {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: #ff9800; /* 橙色风格 */
}

.use-button[disabled] {
  background-color: #ccc;
  color: #666;
  opacity: 0.7;
}

.refund-button {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: #9c27b0; /* 紫色风格 */
}

.empty-tip {
  color: #999;
  font-size: 36rpx;
  text-align: center;
}

.content {
  text-align: left;
  padding: 20rpx;
}

page{
  background-color: #eaeaea; /* 页面整体底色 */
}
.order{
  background-color: #eaeaea;
  display: flex;
  flex-direction: column;
  min-height: 100vh; /* 改为 vh 单位，确保占满屏幕 */
}
.order-title {
  display: flex;
  justify-content: space-between;
  align-items: center; /* 修改：调整对齐方式 */
  padding: 20rpx;
  color: black;
  font-weight: bold;
  background-color: white;
}
/* 导航指示器样式 */
.indicator {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
  background-color: white;
  border-bottom: 2px solid lightgray;
}
.indicator-item {
  padding: 10rpx 40rpx;
  border-radius: 7rpx;
  background-color: #faf1f1;
  font-size: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100rpx;
}
.indicator-icon {
  width: 50rpx;
  height: 50rpx;
  margin-bottom: 10rpx;
}
.title{
  font-size: 30rpx;
  font-weight: bold;
}
.indicator-item.active {
  background-color: #ff3c00;
  color: #fff;
}
.content-container {
  padding: 20rpx;
  background-color: #eeeeee;
  height:100vh ;
}

.order-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;
  border-radius: 10rpx;
}
.order-item view {
  margin-bottom: 10rpx;
}

.payment-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.dialog-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: white;
  border-radius: 10rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.dialog-header .close-icon {
  width: 40rpx;
  height: 40rpx;
}

.dialog-body .amount {
  font-size: 32rpx;
  margin-bottom: 40rpx;
}

.pay-now-button {
  background-color: #2196f3;
  color: white;
  font-size: 28rpx;
  padding: 15rpx 0;
  border-radius: 40rpx;
}

.payment-methods {
  margin-bottom: 30rpx;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
}

.method-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.method-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.checkmark {
  width: 40rpx;
  height: 40rpx;
}
</style>